﻿using Hangfire.HttpJob.CSRedis.JobAgent;
using Hangfire.HttpJob.CSRedis.JobAgent.Middleware;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;

namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// agent job扩展
    /// </summary>
    public static class HangfireAgengJobExtension
    {
        /// <summary>
        /// 注入hangfire agent job
        /// </summary>
        public static IServiceCollection AddHangfireAgent(this IServiceCollection services)
        {
            services.AddHttpClient();
            services.AddHttpContextAccessor();
            RegisterJob(services);
            return services;
        }

        /// <summary>
        /// hangfire agent job
        /// </summary>
        /// <param name="app">IApplicationBuilder</param>
        /// <param name="agentPath">远程作业监听路径,默认/agent_job</param>
        public static IApplicationBuilder UseHangfireAgentJob(this IApplicationBuilder app, string agentPath = "/agent_job")
        {
            agentPath = string.IsNullOrWhiteSpace(agentPath) ? "/agent_job" : agentPath;
            app.MapWhen(httpContext => httpContext.Request.Path.Value.StartsWith(agentPath),
               builder => builder.UseMiddleware<AgentJobMiddleware>());
            return app;
        }

        #region private methods
        /// <summary>
        /// 注册实现了IAgentJob的非泛型类
        /// </summary>
        private static void RegisterJob(this IServiceCollection services)
        {
            if (services != null)
            {
                var jobTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(m => m.GetTypes())
                .Where(m => m.IsPublic && m.IsClass && !m.IsAbstract && !m.IsGenericType && typeof(IAgentJob).IsAssignableFrom(m));
                foreach (var type in jobTypes)
                {
                    services.AddScoped(typeof(IAgentJob), type);
                }
            }
        }
        #endregion
    }
}
